import Vue from 'vue';
import Router from 'vue-router';
import Layout from '@/layout'
import util from '@/utils/myutils.js'
import {
    permissionsFlag
} from '@/api/userController'
import moduleRoutes from './modules/index'
import that from '../main.js'
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

Vue.use(Router);

const routes = [
    //登录
    {
        path: '/',
        redirect: '/login',
    },
    {
        path: '/login',
        component: () => import('@/view/login'),
        meta: {
            title: '默通工单',
        }
    },
    {
        path: '/farmBoard',
        component: Layout,
        redirect: '/farmBoard/procedureNotice',
        children: [{
            path: '/farmBoard/procedureNotice',
            component: () => import('@/view/farmBoard/procedureNotice'),
            meta: {
                title: '默通工单',
                breadList: [{
                    name: '车间看板',
                    to: '/farmBoard'
                }, {
                    name: '工序看板',
                    to: ''
                }],
                permCode: 'workshop.procedureNotice'
            }
        }]
    },
    {
        path: '/board',
        component: () => import('@/view/farmBoard/board'),
        meta: {
            permCode: "workshop.kanban.1",
            title: '默通工单',
        }
    },
    {
        path: '/orderProgress',
        component: () => import('@/view/farmBoard/orderProgress'),
        meta: {
            permCode: "workshop.kanban.2",
            title: '默通工单',
        }
    },

    {
        path: '/404',
        component: () => import('@/view/error/404'),
        meta: {
            title: '默通工单',
        }
    },
    {
        path: '*',
        redirect: '/404'
    },
    ...moduleRoutes
];

// add route path
// routes.forEach(route => {
//     route.path = route.path || '/' + (route.name || '');
// });

const router = new Router({
    mode: 'history',
    routes
});

//权限列表
const getPermissionsFlag = (permCode, to) => {
    permissionsFlag({
        permCode
    }).then(res => {
        if (res.code == 200) {
            that.$store.commit('setAuth', res.data.blPerm)
        }
    })
}

router.beforeEach((to, from, next) => {
    console.log(to,'to')
    const title = to.meta && to.meta.title;
    if (title) document.title = title

    if (to.path != '/login') {
        //禁止未登录输入url跳转其他页面
        if (!localStorage.getItem('token')) {
            util.showMsg('请登录', 'error')
            next('/login')
        } else {
            getPermissionsFlag(to.meta.permCode, to)
            next()
        }
    } else {
        next()
    }
});

export {
    router
};